package com.xes.rabbitmq.consumer.component;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.xes.rabbitmq.core.domain.tables.pojos.TbStudent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class StudentReceiver {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 消费者操作
     *
     * @param student
     * @param headers
     * @param channel
     */
    @RabbitHandler
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = "student-exchange", durable = "true", type = "topic"),
            key = "student-#",
            value = @Queue(value = "student-queue", durable = "true")
    ))
    public void onMessage(@Payload TbStudent student, @Headers Map<String, Object> headers,
                          Channel channel) throws Exception {
        log.info("收到消息内容：{}", JSON.toJSONString(student));

        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        log.info("deliveryTag={}", deliveryTag);

        channel.basicQos(100);

        channel.basicAck(deliveryTag, false);
    }
}
